<template>
  <div>
    <a-form-model
      :model="formData"
      class="AsteriskAfter newEditStyle"
      :rules="rules"
      :colon="false"
      ref="validateForm">
      <div class="carModelItem" v-if="!isReadonly">
        <div class="label">
          <div class="carPic" @click="changeSelect('none')">
            <p>未参与车型管理</p>
            <p>无关联车型</p>
          </div>
          <a-checkbox class="checkBox" :disabled="isReadonly" :checked="selectedCarBrand.includes('none')" style="border-radius: 50%;" @change="changeSelect('none')"></a-checkbox>
          <p class="keyWord">负责软件可售会员售卖业务运营，及相关未参与车型管理人员可选择此项</p>
        </div>
      </div>
      <!-- 比亚迪汽车 -->
      <div class="carModelItem" v-for="brand in config">
        <div class="label">
          <img class="carPic" :src="require(`@assets/${brand.key}.png`)" alt="" @click="changeSelect(brand.key)">
          <a-checkbox class="checkBox" style="border-radius: 50%;" :checked="selectedCarBrand.includes(brand.key)" @change="changeSelect(brand.key)"></a-checkbox>
        </div>
        <div :style="{'opacity' : selectedCarBrand.includes(brand.key) ? '1' : '0.6'}" v-if="!isReadonly && selectedCarBrand.includes(brand.key)">
          <a-table
            :ref="`${brand.key}Table`"
            :scroll="{y:250,x:500}"
            :columns="columns"
            :data-source="formData[brand.key]"
            :rowKey="(record, index) => {return index}"
            :pagination="false"
            style="margin-top:10px"
            :rowSelection="getRowSelection(brand.selectRow, brand.onChange)"
          >
            <!-- 车型名称 -->
            <template slot="modelName" slot-scope="text,record,index">
              <a-form-model-item
                :prop="brand.key + '.'+index+'.modelName'"
                :rules="rules.modelName">
                <car-model-select
                  mode="default"
                  :query="{company:[brand.company], selectAll:true}"
                  :has-all="false"
                  v-model="record.modelId"
                  :clear="true"
                  :getPopupContainer="$commonFun.getPopupContainer"
                  @changeoption="(val, item) => changeModel(val, item, record, brand)"
                  placeholder="请输入所管理的车型对应车型名称"
                />
              </a-form-model-item>
            </template>
            <!-- 车型代码 -->
            <template slot="modelCode" slot-scope="text,record,index">
              <a-form-model-item
                :prop="brand.key + '.'+index+'.modelCode'"
                :rules="rules.modelCode">
                <a-input v-model="record.modelCode" :maxLength="15" placeholder="请输入车型代码" :disabled="record.hasModelname"/>
              </a-form-model-item>
            </template>
            <!-- 车辆款型名称 -->
            <template slot="modelStyleName" slot-scope="text,record,index">
              <a-form-model-item
                :prop="brand.key + '.'+index+'.modelStyleName'"
                :rules="rules.modelStyleName"
              >
                <a-input v-model="record.modelStyleName" :max-length="50" placeholder="请输入车辆款型名称" :disabled="!selectedCarBrand.includes(brand.key)"></a-input>
              </a-form-model-item>
            </template>
            <!-- DiLink系统平台 -->
            <template slot="DiLinks" slot-scope="text,record,index">
              <a-form-model-item :prop="brand.key + '.'+index+'.DiLinks'" :rules="rules.diLinks">
                <a-checkbox-group
                  v-model="record.DiLinks"
                  style="width: 100%;"
                  :disabled="!selectedCarBrand.includes(brand.key)"
                >
                  <a-row :gutter="[0,10]">
                    <a-col :span="24">
                      <a-checkbox value="DiLink5.0">
                        DiLink5.0
                      </a-checkbox>
                    </a-col>
                    <a-col :span="24">
                      <a-checkbox value="DiLink6.0">
                        DiLink6.0
                      </a-checkbox>
                    </a-col>
                    <a-col :span="24">
                      <a-checkbox value="other" class="otherBoxInput">其他
                        <a-form-model-item v-if="record.DiLinks.includes('other')" style="width:180px;position: absolute;top:-8px;left:60px" :prop="brand.key+'.'+index+'.otherSystem'" :rules="rules.otherSystem">
                          <a-input type="text" :disabled="!selectedCarBrand.includes(brand.key)" :maxLength="200" v-model="record.otherSystem" placeholder="请输入其他系统平台名称"/>
                        </a-form-model-item>
                      </a-checkbox>
                    </a-col>
                  </a-row>
                </a-checkbox-group>
              </a-form-model-item>
            </template>
            <!-- 涉及ECU -->
            <template slot="ecu" slot-scope="text,record,index">
              <a-form-model-item
                :prop="brand.key+'.'+index+'.ecu'"
                :rules="rules.ecu">
                <a-input v-model="record.ecu" :disabled="!selectedCarBrand.includes(brand.key)" :max-length="500" placeholder="请输入"></a-input>
              </a-form-model-item>
            </template>
          </a-table>
          <div style="display:flex">
            <div :class="['operationButton',selectedCarBrand.includes(brand.key)?'':'cancelPointer']" style="color:blue" @click="addCarBrand(brand.key)"><a-icon type="plus" />新建一行</div>
            <div :class="['operationButton',selectedCarBrand.includes(brand.key)?'':'cancelPointer']" style="color:red" @click="deleteCarBrand(brand.key)"><a-icon type="close" />删除一行</div>
          </div>
        </div>
        <div v-if="isReadonly">
          <a-table
            :scroll="{y:250}"
            :columns="columns"
            :data-source="formData[brand.key]"
            :rowKey="(record, index) => {return index}"
            :pagination="false"
            style="margin-top:10px"
          >
            <template slot="DiLinks" slot-scope="text">
              {{text.join(',')}}
            </template>
          </a-table>
        </div>
      </div>
    </a-form-model>
  </div>
</template>

<script>
  import { CarBrandSelectColumns } from '@/views/user/config/list.js'
  import lodash from 'lodash'
  import CarModelCodeSelect from '@/views/components/CarModelCodeSelect'
  import CarModelSelect from '@/views/components/CarModelSelect'
  import {checkTextLen} from "@/utils/validate";
  const carInfo={
    modelName: undefined,
    modelCode: undefined,
    modelStyleName: undefined,
    DiLinks: [],
    ecu: '',
    hasModelname:false
  }
  export default {
    components:{
      CarModelSelect,
      CarModelCodeSelect
    },
    props:{
      isReadonly:{
        type:Boolean,
        default:false
      },
      carBrandInfo:{
        type: Object,
        default() {
          return {}
        }
      }
    },
    data(){
      let config = [
        {
          key: 'bydCar',
          company: 'BYD',
          onChange: 'onBYDSelectChange',
          selectRow: 'BYDselectedRowKeys',
        },
        {
          key: 'tsCar',
          company: 'DENZA',
          onChange: 'onTSSelectChange',
          selectRow: 'TSselectedRowKeys',
        },
        {
          key: 'ywCar',
          company: 'YANGWANG',
          onChange: 'onYWSelectChange',
          selectRow: 'YWselectedRowKeys',
        },
      ];
      let formData = {};
      config.forEach(value => {
        formData[value.key] =  [{
          modelId: undefined,
          modelName: undefined,
          modelCode: undefined,
          modelStyleName: undefined,
          DiLinks: [],
          ecu: '',
          hasModelname:false
        }];
      });
      return {
        selectedCarBrand:[],
        // 已选中的表格行keys
        selectedRowKeys: [],
        BYDselectedRowKeys: [],
        TSselectedRowKeys: [],
        YWselectedRowKeys: [],
        columns:CarBrandSelectColumns,
        config,
        formData,
        rules:{
          // 比亚迪
          modelName: [{ required: true, message: this.$t('pleaseSelect') }],
          modelCode:[{ required: true, message: this.$t('pleaseSelect') }],
          diLinks: [{ validator:(rule, value, callback) => {
              if (value.length==0) {
                callback(new Error(this.$t('pleaseSelect')));
              } else {
                callback();
              }
            } }],
          modelStyleName: [{ required: true, message: this.$t('pleaseInput') }],
          otherSystem:[{ required: true, message: this.$t('pleaseInput') }],
          ecu:[{ required: true, message: this.$t('pleaseInput') }],
        }
      }
    },
    watch:{
      carBrandInfo:{
        handler(value){
          if(value){
            const formData=lodash.cloneDeep(value)
            if(formData.brands && formData.brands.length>0){
              formData.brands.forEach(item=>{
                let conf = this.config.find(c => c.company === item.company);
                if (conf) {
                  this.formData[conf.key]=item.models
                  this.selectedCarBrand.push(conf.key)
                  this.formData[conf.key].forEach(item=>{
                    if(item.otherSystem){
                      item.DiLinks.push('other')
                      item.DiLinks.splice(item.DiLinks.indexOf(item.otherSystem),1)
                    }
                    if(!item.modelId){
                      item.modelId = item.modelCode;
                    }
                  })
                }
              })
              if(this.selectedCarBrand.includes('none')){
                this.selectedCarBrand=this.selectedCarBrand.filter(item=>{
                  return item!=='none'
                })
              }
            }else{
              this.selectedCarBrand.push('none')
            }
          }
        },
        immediate:true,
        deep:true
      }
    },
    mounted(){
    },
    methods:{
      getRowSelection(dataKey, methodName) {
        return {columnTitle: ' ', selectedRowKeys: this[dataKey], onChange: this[methodName]}
      },
      changeModel(val, item, record, brand){
        if(val && this.formData[brand.key].filter(item => item.modelId === val).length > 1) {
          this.$message.warning('同一品牌下车型不可重复')
          this.$nextTick(()=>{
            this.changeModel(undefined, null, record, brand);
          })
          return;
        }
        record.hasModelname= !!val;
        this.$set(record,'modelId',item?.id);
        this.$set(record,'modelCode',item?.code);
        this.$set(record,'modelName',item?.modelName);
        this.$refs.validateForm.clearValidate()
      },
      onGetCheckboxProps: record => ({
        // 车型品牌没有被选择时或者只有一条数据时不可使用
        props: {
          // disabled:true
        }
      }),
      // 新增车型
      addCarBrand(brand){
        if(!this.selectedCarBrand.includes(brand)){
          return
        }
        this.formData[brand].push(lodash.cloneDeep(carInfo))
      },
      // 删除车型
      deleteCarBrand(brand){
        if(!this.selectedCarBrand.includes(brand)){
          return
        }
        let conf = this.config.find(item => item.key === brand);
        if (conf) {
          if(this[conf.selectRow].length>1){
            this.$message.warning('每次只能选择一行数据做删除操作！')
            return
          }
          this[conf.selectRow].forEach(item=>{
            this.formData[brand].splice(item,1)
          });
          this[conf.selectRow]=[];
        }
        this.$refs.validateForm.clearValidate()
      },
      // 选中某一行
      onBYDSelectChange (selectedRowKeys) {
        this.BYDselectedRowKeys = selectedRowKeys
      },
      onTSSelectChange (selectedRowKeys) {
        this.TSselectedRowKeys = selectedRowKeys
      },
      onYWSelectChange (selectedRowKeys) {
        this.YWselectedRowKeys = selectedRowKeys
      },
      // 选中某一车型品牌
      changeSelect(data){
        if(this.isReadonly){
          return
        }
        this.$refs.validateForm.clearValidate()
        let vm=this
        if(this.selectedCarBrand.includes(data)){
          this.selectedCarBrand.splice(this.selectedCarBrand.indexOf(data),1)
          this.formData[data]=[lodash.cloneDeep(carInfo)]
        }else{
          this.selectedCarBrand.push(data)
        }
        if(this.selectedCarBrand.includes('none') && data=='none' && this.selectedCarBrand.length>1){
          this.$confirm({
            title: '确定要清空车型品牌录入信息，切换到[未参与车型管理]选项吗？',
            content: '执行该操作后,已录入的所有车型品牌数据将会被清空',
            onOk() {
              vm.selectedCarBrand=[data]
              vm.formData.bydCar=[lodash.cloneDeep(carInfo)]
              vm.formData.tsCar=[lodash.cloneDeep(carInfo)]
              vm.formData.ywCar=[lodash.cloneDeep(carInfo)]
            },
            onCancel() { vm.selectedCarBrand.splice(vm.selectedCarBrand.indexOf('none'),1) },
          });
        }
        if(data!='none' && this.selectedCarBrand.includes('none')){
          this.selectedCarBrand=this.selectedCarBrand.filter(item=>{
            return item!=='none'
          })
        }
      },
      getFormData(){
        return new Promise(((resolve, reject) => {
          this.$refs.validateForm.validate((valid) => {
            if (!valid) {
              return reject();
            }
            try {
              const data={
                brands:[]
              }
              const formData = lodash.cloneDeep(this.formData)
              this.selectedCarBrand.forEach(key => {
                if (!formData[key]) {
                  return;
                }
                formData[key].forEach((item)=>{
                  if(item.DiLinks.includes('other')){
                    item.DiLinks.splice(item.DiLinks.indexOf('other'),1)
                    item.DiLinks.push(item.otherSystem)
                  }
                });
                data.brands.push({
                  company: this.config.find(c => c.key === key).company,
                  models: formData[key]
                })
              })
              if(this.selectedCarBrand.length>0){
                resolve(data);
              }else{
                this.$message.warning('请选择管理车型品牌')
                reject();
              }
            }catch (e) {
              reject(e);
            }
          })
        }))
      }
    }
  }
</script>

<style lang="less" scoped>
  .carModelItem{
    margin-bottom: 20px;
  }
  .label{
    position: relative;
    border-bottom: 2px solid #fff;
    .carPic{
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background-color: #BBBBBB;
      width:180px;
      height: 83px;
      border-radius: 8px;
      border: 4px solid #fff;
      cursor: pointer;
    }
    .checkBox{
      position: absolute;
      left: 160px;
      bottom: 0;
    }
    .checkBox ::v-deep .ant-checkbox-inner{
      border-radius: 50%;
    }
    .keyWord{
      position: absolute;
      left: 200px;
      top: 30px;
      color: #888888;
      font-weight: bold;
    }
  }
  .operationButton{
    width: 50%;
    height: 30px;
    background: #fff;
    border: 1px solid #BBBBBB;
    border-bottom-left-radius: 30px;
    border-bottom-right-radius: 30px;
    text-align: center;
    line-height: 30px;
    cursor: pointer;
  }
  .cancelPointer{
    cursor: auto;
  }
  ::v-deep .ant-table-row{
    background-color: #fff;
  }
  ::v-deep .ant-checkbox-wrapper{
    margin-left:0
  }
  /deep/.ant-form-explain {
    position: absolute;
    font-size: 1rem;
  }
  .otherBoxInput .ant-input{
    border:none;
    border-bottom: 1px solid #000;
    border-radius: 0;
  }
</style>